/**
 * 添加/编辑商品
 */
 var getImageHtml = function(imgUrl,delFunName,index,width,height){
	 console.log(width+'----------------'+height);
    return "<div class=\"am-u-sm-4 am-u-md-4\">"
          +"<img width=\"100%\" src=\""+imgUrl+"\" alt=\"预览图\"/><span>"+width+" * "+height+" px</span>"
          +"<div class=\"am-text-center am-text-primary am-margin-top-xs\" onclick=\""+delFunName+"(this)\">删除</div>"
          +"</div>";
 };

 var warning_img_size = function(){
    alert("为保证显示效果，请尽量上传480*660 至 720*990 像素的图片");
 }

 var callback = function(arr){
	 var newArr = new Array();
	 for(var i=0;i<arr.length;i++){
		 if(arr[i] !=""){
			 newArr.push(arr[i]);
		 }
	 }
	 return newArr;
 }

 var showBannerImg = function(banner_img_urls){
    var urlsArr = banner_img_urls.split(",");
    var len = urlsArr.length;
    for(var i=0;i<len;i++){
      if(urlsArr[i]){
    	  console.log("url===== "+urlsArr[i]);
    	var imgWidth = 0;
    	var imgHeight = 0;
    	$.ajax({
		   type: "GET",
		   url: base+"/product/imageDetail",
		   data: "url="+urlsArr[i],
		   dataType:"json",
		   async:false,
		   success: function(result){
			   console.log("status=="+result.status+",imgWidth=="+result.imgWidth+",imgHeight==="+result.imgHeight);
			   imgWidth = result.imgWidth;
			   imgHeight = result.imgHeight;
		   }
    	});
        var temp = getImageHtml(urlsArr[i],"deleteBannerImg",null,imgWidth,imgHeight);
        $("#banner-img-preview #banner-img-split").before($(temp));
      }
    }
 };

 
 var urlCheck = function(url){
	 var regEx = "^((https|http|ftp|rtsp|mms)?://)"
	        + "(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
	        + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184  
	        + "|" // 允许IP和DOMAIN（域名） 
	        + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.  
	        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名  
	        + "[a-z]{2,6})" // first level domain- .com or .museum  
	        + "(:[0-9]{1,4})?" // 端口- :80  
	        + "((/?)|" // a slash isn't required if there is no file name  
	        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 
     var regexp = new RegExp(regEx);
     console.log(" regexp.test(url)====="+ regexp.test(url));
     return regexp.test(url);
 }
 
 
$(function() {
	console.log("base="+base);
  /*表单验证：begin*/
  var $myField = null;
  var myMsg = "";




  $("#frm").validator({
    // 域通过验证时回调
    onValid: function(validity) {
      $(validity.field).closest('.am-form-group').find('.am-alert').hide();
    },
    // 验证出错时的回调， validity 对象包含相关信息，格式通 H5 表单元素的 validity 属性
    onInValid: function(validity) {
      var $field = $(validity.field);
      var $group = $field.closest('.am-form-group');
      var $alert = $group.find('.am-alert');
      var msg = "";
      if($myField && myMsg && $field.val() && $field.is($myField)){
        msg = myMsg;
        $myField = null;
        myMsg = "";
      }else{
        // 使用自定义的提示信息 或 插件内置的提示信息
        msg = $field.data('validationMessage') || this.getValidationMessage(validity);
      }

      if (!$alert.length) {
        $alert = $("<div class='am-alert am-alert-danger'></div>").hide().
        appendTo($group.find(".input-msg"));
      }
      console.log("onInValid : "+$field.val());
      $alert.html(msg).show();
    },
    //自定义验证
    validate: function(validity) {
    	// 在这里编写你的验证逻辑
        var v = $(validity.field).val();
        var comparer = function(v1, v2) {
        	//if (v1 <= v2) {
        	if(DateTimeCompare(v1, v2)){
        		validity.valid = false;
        	}
        };
        
        if ($(validity.field).is('#end_time')){
        	var put_on_time = $('#start_time').val();
        	var put_off_time = $('#end_time').val();
        	comparer(put_on_time, put_off_time);
        }
    },
    submit: function() {
      var formValidity = this.isFormValid();
      var imageUrl = $("#promo_img").val();       
      if(imageUrl==null || imageUrl.length==0){
          showImageInvalidAlert("请上传弹窗图片");
          return false;
      }
      
      if($("#url").val()!="" && !urlCheck($("#url").val())){
    	  showUrlInvalidAlert("url格式有误");
    	  return false;
      }
      // 表单验证成功，弹出确认提示
      if (formValidity) {
        if(confirmSubmit()){
          return true;
        }       
      }
      console.warn('验证状态：', formValidity ? '通过' : '未通过');
      return false;
    }
  });
  
  /*表单验证：end*/
	/*展示图附件上传：begin*/
    var jqXHR = $('#promo_fileupload').fileupload({
      url: base+"/upload/image",
      dataType: 'json',
      start: function (e) {

        console.log("promo_fileupload start ");
        $("#progress-area").removeClass("am-hide");
        $("#progress-text").removeClass("am-text-danger");
        $("#progress-text").html("");
        $(".am-progress-bar").css("width","0%");
      },
      done: function (e, data) {
        if(data.result.status=="error"){
        	$("#progress-text").addClass("am-text-danger");
        	showImageInvalidAlert(data.result.message);
        	setTimeout(function() {
        		$("#progress-area").addClass("am-hide");
        	},1500);
        	return false;
        }
        var img=$("#promo_img").val();
        $("#promo_img").val(data.result.url);
        var temp = getImageHtml(data.result.url,"deleteBannerImg",null,data.result.imgWidth,data.result.imgHeight);
        var pre =$(temp);
        $("#banner-img-preview").html(pre);
        $("#banner-img-preview").parent().removeClass("am-hide");
        setTimeout(function() {
          $("#progress-area").addClass("am-hide");
        },1500);
        clearImageValidInfo("");
      },
      progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $(".am-progress-bar").css("width",progress + "%");
        $("#progress-text").html(progress + "%");
      },
      error: function (jqXHR, textStatus, errorThrown) {
        console.log("imageupload error！");
        $("#progress-area").removeClass("am-hide");
        $("#progress-text").addClass("am-text-danger");
        $("#progress-text").html("imageupload error！");
        $(".am-progress-bar").css("width","0%");
        setTimeout(function() {
          $("#progress-area").addClass("am-hide");
        },2000);
      },
      fail: function (jqXHR, textStatus) {
        console.log("imageupload fail！");
        $("#progress-area").removeClass("am-hide");
        $("#progress-text").addClass("am-text-danger");
        $("#progress-text").html("imageupload fail！");
        $(".am-progress-bar").css("width","0%");
        setTimeout(function() {
          $("#progress-area").addClass("am-hide");    
        },2000);
      }
    });
    /*附件上传：end*/	
  var promotionId = $("#promotionId").val();
  if(promotionId){
    $.each($(".am-tabs").find("li"),function(){
      if($(this).attr("id") == "sel-category"){
        $(this).addClass("am-hide")
        $(this).removeClass("am-active");
        $("#info").addClass("am-active");
        $("#category").removeClass("am-active");
      }else{
        $(this).removeClass("am-hide");
        if($(this).attr("id") == "base-info"){
          $(this).addClass("am-active");
        }
      }
    });
    $("#confirm-btns").addClass("am-hide");
    $("#submit-btns").removeClass("am-hide");
    //显示图片
    var banner_img_urls = $("#promo_img").val();
    if(banner_img_urls){
      showBannerImg(banner_img_urls);
      $("#banner-img-preview").parent().removeClass("am-hide");
    }
  }
});

function deleteBannerImg(obj) {
	console.log("deleteBannerImg");
	$obj = $(obj);
	var img=$("#promo_img").val();
	$("#promo_img").val("");
  $obj.parent().empty();
  
  if(!($("#promo_img").val())){
    $("#banner-img-preview").parent().addClass("am-hide");
  }else{
    $("#banner-img-preview").parent().removeClass("am-hide");
  }
}

function deleteThumbnailImg(obj) {
	console.log("deleteThumbnail");
	$obj = $(obj);
	var img=$("#thumbnail").val("");
  $obj.parent().parent().empty();
  $("#thumbnail-preview").parent().addClass("am-hide");
}
function clearImageValidInfo(){
    showImageInvalidAlert("");
}
function showImageInvalidAlert(message){
  var $alert = $("#image_valid").find('.am-alert');
  if (!$alert.length) {
    $alert = $('<div class="am-alert am-alert-danger"></div>').hide()
    $alert.appendTo($("#image_valid"));
  }
  if(message.length==0){    
    $alert.hide();
  }else{    
	  $alert.text(message).show();
    setTimeout(function() {
		$alert.text(message).show();
	},50);
  }
}

function showImageInvalidAlert(message){
	  var $alert = $("#image_valid").find('.am-alert');
	  if (!$alert.length) {
	    $alert = $('<div class="am-alert am-alert-danger"></div>').hide()
	    $alert.appendTo($("#image_valid"));
	  }
	  if(message.length==0){    
	    $alert.hide();
	  }else{    
		  $alert.text(message).show();
	    setTimeout(function() {
			$alert.text(message).show();
		},50);
	  }
}



function showUrlInvalidAlert(message){
	  var $alert = $("#urlErrMsg").find('.am-alert');
	  if (!$alert.length) {
	    $alert = $('<div class="am-alert am-alert-danger"></div>').hide()
	    $alert.appendTo($("#urlErrMsg"));
	  }
	  if(message.length==0){    
	    $alert.hide();
	  }else{    
		  $alert.text(message).show();
	    setTimeout(function() {
			$alert.text(message).show();
		},50);
	  }
}

